package com.alvin.springshiro.shiro;

import com.alvin.springshiro.model.Permission;
import com.alvin.springshiro.model.Role;
import com.alvin.springshiro.model.User;
import com.alvin.springshiro.service.UserRolePermissionService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private UserRolePermissionService userRolePermissionService;

    /**
     * 获取授权（Authorization）
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取登录用户名
        String name = (String) principalCollection.getPrimaryPrincipal();
        //根据用户名去数据库查询用户信息
        User user = userRolePermissionService.getUserByUserName(name);
        //获取用户角色
        List<Role> userRole = userRolePermissionService.getUserRols(user.getId());
        //获取用于权限
        List<Permission> userPermission = userRolePermissionService.getUserPermissions(user.getId());
        //添加角色和权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        //添加角色
        for (Role role : userRole) {
            simpleAuthorizationInfo.addRole(role.getName());
        }
        //添加权限
        for (Permission permission : userPermission) {
            simpleAuthorizationInfo.addStringPermission(permission.getName());
        }
        return simpleAuthorizationInfo;
    }

    /**
     * 验证授权（Authentication）
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //加这一步的目的是在Post请求的时候会先进认证，然后再到请求
        if (authenticationToken.getPrincipal() == null) {
            return null;
        }
        //获取用户信息
        String name = authenticationToken.getPrincipal().toString();
        User user = userRolePermissionService.getUserByUserName(name);
        if (user == null) {
            //这里返回后会报出对应异常
            return null;
        } else {
            //这里验证authenticationToken和simpleAuthenticationInfo的信息
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user.getName(), user.getPassword(), ByteSource.Util.bytes(user.getSalt()), getName());
            return simpleAuthenticationInfo;
        }
    }
}
